package com.wlbx.agent.ui.activity;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.StringUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索历史
 */
public class SearchActivity extends BaseActivity {

    @BindView(R.id.tfl_activity_search)
    TagFlowLayout mHistoryTFL;


    @BindView(R.id.iv_back)
    ImageView ivBack;


    @BindView(R.id.tv_search)
    TextView tvSearch;

    @BindView(R.id.iv_clear_history)
    ImageView ivClearHistory;
    @BindView(R.id.et_search)
    EditText etSearch;

    @BindView(R.id.iv_clear)
    ImageView ivClear;


    private List<String> mHistoryList = new ArrayList<>();
    private String flag;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_search;
    }

    @Override
    public void initData() {
        Constant.FINGER_PRINT=false;
        Constant.INSTALL_LATER=false;
        initHistory();
        etSearch.setFocusable(true);
        etSearch.setFocusableInTouchMode(true);
        etSearch.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                InputMethodManager inputManager =
                        (InputMethodManager) etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(etSearch, 0);
            }

        }, 500);
        etSearch.setText(Constant.PRODUCT_NAME);
        etSearch.setSelection((Constant.PRODUCT_NAME).length());
        flag=getIntent().getStringExtra("flag");
        Logger.i("flag---"+flag);
    }


    @Override
    public void initEvent() {
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Logger.i("actionId>>>>>>" + actionId);
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keyword = etSearch.getText().toString().trim();
                    if (!TextUtils.isEmpty(keyword)){
                        mHistoryList.add(keyword);
                    }
                    setHistoryList(removeDuplicate(mHistoryList));
                    if (flag.equals("product")){
                        finish();
                    }else {
                        IntentUtil.goMainActivity("1",SearchActivity.this);
                    }

                    UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                    updateProductListEvent.setProductName(keyword);
                    updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                    updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                    updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                    EventBus.getDefault().postSticky(updateProductListEvent);
                    Logger.i("post关键字---"+JSON.toJSONString(updateProductListEvent));
                    Constant.PRODUCT_NAME=keyword;
                    etSearch.setText(keyword);



                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)){
                    ivClear.setVisibility(View.INVISIBLE);
                }else {
                    ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(etSearch.getText().toString())){
            ivClear.setVisibility(View.INVISIBLE);
        }else {
            ivClear.setVisibility(View.VISIBLE);
        }
    }

    public static List<String> removeDuplicate(List<String> list) {
        Set set = new LinkedHashSet<String>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }

    public void setHistoryList(List<String> history) {
        String listStr;
        try {
            listStr = StringUtil.list2String(history);
            SPUtil.put(Constant.SEARCH_HISTORTY, listStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public List<String> getHistoryList() {
        List<String> list = new ArrayList<String>();
        String history = (String) SPUtil.get(Constant.SEARCH_HISTORTY, "");
        try {
            list = StringUtil.string2List(history);
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initHistory() {
        Logger.i(JSON.toJSONString(getHistoryList()));
        mHistoryList=getHistoryList();
        if (mHistoryTFL != null) {
            mHistoryTFL.setAdapter(new TagAdapter<String>(mHistoryList) {
                @Override
                public View getView(FlowLayout parent, int position, final String s) {
                    LinearLayout view = (LinearLayout) mInflater.inflate(R.layout.item_search, null);
                    TextView textView = (TextView) view.findViewById(R.id.tv_text);
                    textView.setText(s);
                    return view;
                }
            });
            mHistoryTFL.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {
                    if (flag.equals("product")){
                        finish();
                    }else {
                        IntentUtil.goMainActivity("1",SearchActivity.this);
                    }
                    UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                    updateProductListEvent.setProductName(mHistoryList.get(position));
                    updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                    updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                    updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                    EventBus.getDefault().postSticky(updateProductListEvent);
                    Constant.PRODUCT_NAME=mHistoryList.get(position);
                    etSearch.setText(mHistoryList.get(position));
                    return true;
                }
            });
        }
    }

    @OnClick({R.id.iv_back, R.id.tv_search, R.id.iv_clear_history,R.id.iv_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                String keyword = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    mHistoryList.add(keyword);
                }
                setHistoryList(removeDuplicate(mHistoryList));

                if (flag.equals("product")){
                    finish();
                }else {
                    IntentUtil.goMainActivity("1",SearchActivity.this);
                }
                UpdateProductListEvent updateProductListEvent = new UpdateProductListEvent();
                updateProductListEvent.setProductName(keyword);
                updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                EventBus.getDefault().postSticky(updateProductListEvent);
                Logger.i("post关键字---" + JSON.toJSONString(updateProductListEvent));
                Constant.PRODUCT_NAME=keyword;
                etSearch.setText(keyword);


                break;
            case R.id.iv_clear_history:
                Toast.makeText(SearchActivity.this, "清除历史记录", Toast.LENGTH_SHORT).show();
                SPUtil.remove(Constant.SEARCH_HISTORTY);
                etSearch.setText("");
                Constant.PRODUCT_NAME="";
                initHistory();
                break;
            case R.id.iv_clear:
                etSearch.setText("");
                break;
            default:
                break;
        }
    }




}
